package com.atguigu.xml;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Date:2021/3/8
 * Author:ybc
 * Description:
 */
public class CreateXMLTest {

    @Test
    public void testCreateXML() throws IOException {
        //创建Document对象
        Document document = DocumentHelper.createDocument();
        //创建标签
        Element userElement = document.addElement("user");
        //将userElement设置为根标签
        document.setRootElement(userElement);
        //在根标签下创建子标签
        Element idElement = userElement.addElement("id");
        Element usernameElement = userElement.addElement("username");
        Element passwordElement = userElement.addElement("password");
        Element ageElement = userElement.addElement("age");
        //为标签设置文本内容
        idElement.setText("1001");
        usernameElement.setText("张三");
        passwordElement.setText("123456");
        ageElement.setText("23");
        //将document输出
        OutputFormat format = new OutputFormat("    ", true);
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("user.xml"), format);
        xmlWriter.write(document);
    }

}
